/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package engine.player;

import GUI.MusicPlayerUI;
import engine.decoder.ID3Decoder;
import engine.linkList.PlayScheduleManager;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/**
 *
 * @author hjp
 */
public class MusicPlayer implements Serializable{

    public transient BufferedInputStream buffer;//初始化的时候，将根据currentPlayTime将流置位
    public transient static PlayerThread playerThread;
    public transient static PlayProgressBarThread playProgressBarThread;
    public transient volatile static boolean playState;//置true表示暂停；置false表示播放
    public  transient volatile boolean isComplete;//无论任何情况，播放线程被结束，则播放进度条线程也结束
    public static int currentPlayTime;//当前某首歌曲播放到的时间
    //单例模式
    public static MusicPlayer musicPlayer = new MusicPlayer();
    
    
    //单例模式
    private MusicPlayer(){
        playerThread = new PlayerThread("playerThread");
        playProgressBarThread = new PlayProgressBarThread("PlayProgressBarThread");
        playState = false;
        isComplete = false;
    }
    
    /**
     * 播放线程
     */
    class PlayerThread implements Runnable{
        private String threadName;
        private Thread thread;
        private Player  player;
        
        PlayerThread(String threadName){
            this.threadName = threadName;
            thread = null;
            player = null;
        }

        @Override
        public void run() {
                //无线循环的while循环是为了自动连续播放
                while(true){
//                    //test
//                    System.out.println(System.currentTimeMillis());
                    isComplete = false;
                    playProgressBarThread.start();
                    try{
                       player  = new Player(buffer);
                       player.play();
                    }catch(JavaLayerException e){
                        //无论任何情况，播放线程被结束，则播放进度条线程也结束
                        isComplete = true;
                        player.close();
                    }
                    if (player.isComplete()) {
                        player.close();
                        currentPlayTime = 0;
                        try {
                            buffer = new BufferedInputStream(new FileInputStream(PlayScheduleManager.getInstance().getNextPlay().info.getFilePath()));
                        } catch (FileNotFoundException ex) {
                             ex.printStackTrace();
                        }
                        //更新musicNameLabel
                        MusicPlayerUI.getInstance().getMusicNameLabel().setText(PlayScheduleManager.getInstance().pCurrentPlayMusicNodeCopy.info.getSongName());
                        //设置currentPlayTimeJSlider以及currentPlayTimeJLabel
                        MusicPlayerUI.getInstance().getCurrentPlayTimeJSlider().setMaximum(PlayScheduleManager.getInstance().pCurrentPlayMusicNodeCopy.info.getTime_Int());
                        MusicPlayerUI.getInstance().getCurrentPlayTimeJSlider().setValue(0);
                        MusicPlayerUI.getInstance().getCurrentPlayTimeJLabel().setText("00:00" +  "/" + PlayScheduleManager.getInstance().pCurrentPlayMusicNodeCopy.info.getTime_String());
                    }
               }
        }

        public void start(){
            if (thread == null) {
                thread = new Thread(this,threadName);
                thread.start();
            }
        }
    }

    /**
     * 播放进度条以及当前播放时间线程
     */
    class PlayProgressBarThread implements Runnable{
        
        private String threadName;
        private Thread thread;
        
        PlayProgressBarThread(String threadName){
            this.threadName = threadName;
            thread = null;
        }
        
        @Override
        public void run() {
            //无论任何情况，播放线程被结束，则播放进度条线程也结束
            while(!isComplete){
                if (playerThread.player != null && playerThread.player.isComplete()){
                    break;
                }
                //更新播放进度条
                ++currentPlayTime;
                MusicPlayerUI.getInstance().getCurrentPlayTimeJSlider().setValue(currentPlayTime);
                //更新当前播放时间标签栏
                String totalTime =  MusicPlayerUI.getInstance().getCurrentPlayTimeJLabel().getText().split("/")[1];
                //格式化输出时间
                String minute = null;
                String second = null;
                if ((currentPlayTime / 60) < 10) {
                    minute = "0" + String.valueOf(currentPlayTime / 60);
                }
                else{
                    minute = String.valueOf(currentPlayTime / 60);
                }
                
                if ((currentPlayTime % 60) < 10) {
                    second = "0" + String.valueOf(currentPlayTime % 60);
                }
                else{
                    second = String.valueOf(currentPlayTime % 60);
                }
                MusicPlayerUI.getInstance().getCurrentPlayTimeJLabel().setText(minute +  ":" + second + "/" + totalTime);
                //播放进度条以及当前播放时间线程将于播放线程同步暂停与恢复
                if (playState) {
                    Thread thread = new Thread(new Runnable(){
                        @Override
                        public void run() {
                            while(true){
                                if (!playState) {
                                    break;
                                }
                            }
                        }
                    },"pauseThread");
                    thread.start();
                    try {
                        thread.join();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                //每隔1秒更新一次
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
        public void start(){
            if (thread == null) {
                thread = new Thread(this,threadName);
                thread.start();
            }
        }
    }
    
    

    //播放MP3文件。
    public void playMp3FileImmediately(String filePath){
        try{
            buffer.close();
            buffer =  new BufferedInputStream(new FileInputStream(filePath));
        }catch(IOException  | NullPointerException e){
            try {
                buffer =  new BufferedInputStream(new FileInputStream(filePath));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }
        //启动播放线程
        playerThread.start();
    }

    public void continuePlay(){
        if (playerThread.thread == null || !playerThread.thread.isAlive()) {
            //启动播放线程
            playerThread.start();
        }
        playState = false;
    }

    //当系统退出的时候需调用它，以更新currentPlayTime
    public void pausePlay(){
        playState = true;
//        File serFile = new File("test.ser");
//        try {
//            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(serFile));
//            out.writeObject(currentPlayTime);
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
    }
    
    //在拖动进度条的时候调用
    public boolean randomPositionPlay(double percent,String filePath){
        try {
            buffer.close();
            buffer =  new BufferedInputStream(new FileInputStream(filePath));
            buffer.skip((long)(ID3Decoder.getv2tagSize(filePath) + percent * (ID3Decoder.getSize())));
        } catch (IOException ex) {
            //当发生IO异常的时候，进度条拖动失败。
            ex.printStackTrace();
            return false;
        }
        //启动播放线程
        playerThread.start();
        return true;
    }
    
//    public static void main(String[] args){
//        MusicPlayer player = new MusicPlayer();
//        player.playMp3File("D:\\CloudMusic\\郑欣宜 - 上心.mp3");
        
//        try {
//            ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.ser"));
//            Integer time = (Integer)in.readObject();
//            BufferedInputStream bufferStream = new BufferedInputStream(new FileInputStream("D:\\CloudMusic\\郑欣宜 - 上心.mp3"));
//            ID3Decoder.decode("D:\\CloudMusic\\郑欣宜 - 上心.mp3");
//            double percent = (time * 1.0 / 1000) / (ID3Decoder.getTime() * 1.0);
//            System.out.println((long)(percent * (ID3Decoder.getSize())));
//            System.out.println(bufferStream.skip((long)(ID3Decoder.getv2tagSize("D:\\CloudMusic\\郑欣宜 - 上心.mp3") + percent * (ID3Decoder.getSize()))));
//            Player player = new Player(bufferStream);
//            player.play();
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        } catch (ClassNotFoundException ex) {
//            ex.printStackTrace();
//        } catch (JavaLayerException ex) {
//            Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex);
//        }
        
//        Scanner sc = new Scanner(System.in);
//        if (sc.nextInt() == 1) {
//            player.pausePlay();
//        }
//        if (sc.nextInt() == 0) {
//            player.continuePlay();
//        }
        
 //   }

}
